import os

import yaml

path_data = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "data/")


class YamlUtil:
    def __init__(self):
        self.path_data = path_data

    def read_extract_yaml(self):
        """读取写入yaml文件数据 """
        with open(self.path_data + "extract.yaml", mode='r', encoding="utf8") as f:
            value = yaml.safe_load(f)
            return value

    def read_user_center_yaml(self, yaml_name, key_name=None):
        with open(self.path_data + yaml_name, mode='r', encoding="utf8") as f:
            value = yaml.safe_load(f)
            if key_name:
                return value[key_name]
            return value

    def extract_case(self, yaml_name, key_name=None):
        value = self.read_user_center_yaml(yaml_name, key_name)[0]
        new_case = []
        for data in value['case_info']:
            new_case.append({"request_info": value['request_info'], "case_info": data})
        return new_case

    # 写入extract.yaml
    def write_extra_yaml(self, data):
        with open(self.path_data + "extract.yaml", mode='a', encoding="utf8") as f:
            # 读取之前的yaml内容
            old_value = self.read_extract_yaml()
            if old_value:
            # 和新传入的数据做结合
                for key, value in data.items():
                    old_value[key] = value
                # 清空数据
                self.clear_extract_yaml()
                yaml.dump(data=old_value, stream=f, allow_unicode=True, sort_keys=False)
            else:
                yaml.dump(data=data, stream=f, allow_unicode=True, sort_keys=False)


    def clear_extract_yaml(self):
        """清理extract.yaml"""
        with open(self.path_data + "extract.yaml", mode='w', encoding="utf8") as f:
            f.truncate()


if __name__ == '__main__':
    data = {"code":200,"data":{"id2":13,"Address":"北京市区东城区1232"}}
    YamlUtil().write_extra_yaml(data)
    print(YamlUtil().read_extract_yaml())





read_yaml = YamlUtil()

# if __name__ == '__main__':
#     data = YamlUtil().extract_case("user_center.yaml", "user_login_new")
#     # print(data)
#     print(YamlUtil().read_extract_yaml())